<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :fullFlag="true" width="70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="128px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="8" v-if="formData.id">
          <el-form-item label="订单号" prop="orderId">
            <el-input v-model="formData.orderId" placeholder="请输入客户手机" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运单号" prop="mainOrderId" required>
            <el-input v-model="formData.mainOrderId" placeholder="请输入运单号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分单号" prop="subOrderId">
            <el-input v-model="formData.subOrderId" placeholder="请输入分单号"/>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="目的地城市" prop="destinationCityId" required>
              <el-select v-model="formData.destinationCityId" placeholder="请选择" filterable remote :remote-method='moreAddress1' :loading="loading1">
                <el-option v-for="(item,index) in destAddressList" :key="index" :value="item.id" :label="item.code+'-'+item.countryName+'-'+item.cityName"/>
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分单号目的地城市" prop="subDestCityId">
              <el-select v-model="formData.subDestCityId" placeholder="请选择" filterable remote :remote-method='moreAddress2' :loading="loading2">
                <el-option v-for="(item,index) in destAddressList2" :key="index" :value="item.id" :label="item.code+'-'+item.countryName+'-'+item.cityName"/>
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客服" prop="serviceId">
            <el-input v-model="formData.serviceName" placeholder="请输入客服" :readonly="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="授权给他人" prop="serviceGrantStatus">
            <el-switch v-model="formData.serviceGrantStatus" :active-value="1" :inactive-value="0"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.serviceGrantStatus == 1">
          <el-form-item label="被授权客服" prop="serviceOtherId">
            <el-select v-model="formData.serviceOtherId" placeholder="请选择" filterable>
                <el-option v-for="(item,index) in kefuList" :key="index" :value="item.id" :label="item.nickname"/>
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="件数" prop="warehouseNumber" required>
            <el-input v-model="formData.warehouseNumber" placeholder="请输入件数"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="重量(kg)" prop="weight">
            <el-input v-model="formData.weight" placeholder="请输入重量"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="体积" prop="volume">
            <el-input v-model="formData.volume" placeholder="请输入体积"/>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <el-form-item label="是否随机" prop="randomFlag">
            <el-switch v-model="formData.randomFlag" :active-value="1" :inactive-value="0"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="通关" prop="customsClearance">
            <el-input v-model="formData.customsClearance" placeholder="请输入通关"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否通过仓库" prop="storage">
            <el-switch v-model="formData.storage" :active-value="1" :inactive-value="0"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.storage == 1">
          <el-form-item label="是否需要特殊防护" prop="specialProtection">
            <el-switch v-model="formData.specialProtection" :active-value="1" :inactive-value="0"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.storage == 1">
          <el-form-item label="是否自带危包" prop="comesDangerousBag">
            <el-switch v-model="formData.comesDangerousBag" :active-value="1" :inactive-value="0"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="地服 CA/BGS" prop="theGround" required>
            <el-select v-model="formData.theGround" placeholder="请选择地服 CA/BGS">
              <el-option label="CA" :value="1"/>
              <el-option label="BGS" :value="2"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户公司" prop="companyId" required>
            <el-select v-model="formData.companyId" clearable @change="companyChange">
              <el-option v-for="(item, index) in comList" :key="index" :label="item.companyName" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="主客户" prop="mainCustomerId" required>
            <el-select v-model="formData.mainCustomerId" clearable>
              <el-option v-for="(item, index) in appuserList" :key="index" :label="item.nickName+'-'+item.phoneNumber" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分通知客户1" prop="subCustomerId1">
            <el-select v-model="formData.subCustomerId1" clearable>
              <el-option v-for="(item, index) in appuserList" :key="index" :label="item.nickName+'-'+item.phoneNumber" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分通知客户2" prop="subCustomerId2">
            <el-select v-model="formData.subCustomerId2" clearable>
              <el-option v-for="(item, index) in appuserList" :key="index" :label="item.nickName+'-'+item.phoneNumber" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="装载" prop="freight">
            <el-input v-model="formData.freight" placeholder="请输入装载"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="rac" prop="rac">
            <el-switch v-model="formData.rac" :active-value="1" :inactive-value="0"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="航班号" prop="flightNumber">
            <el-input v-model="formData.flightNumber" placeholder="请输入航班号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="航班日期" prop="flightDate">
            <el-date-picker v-model="formData.flightDate" type="date" placeholder="请选择航班日期" value-format="YYYY-MM-DD"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="品名/型号" prop="productNameMode" required>
            <el-input type="textarea" v-model="formData.productNameMode" placeholder="请输入品名/型号,用“,”隔开" :rows="2"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="包装备注" prop="note">
            <el-input type="textarea" v-model="formData.note" placeholder="请输入包装备注" :rows="2"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类别" prop="mainCategoryCode">
            <div v-for="(item, index) in mainCategoryInfoList" :key="index" style="display:inline-block;width:120px;height:140px;">
                <div style="display:flex;flex-direction:column;align-items:center;">
                    <img style="width:64px;height:64px;" :src="item.src"/>
                    <div style="height:20px;color:000000;font-size:14px;padding-top:10px;">{{item.IMP+' '+item.number}}</div>
                    <div style="height:20px;color:000000;font-size:14px;padding-top:10px;">{{item.text}}</div>
                </div>
            </div>
            <div style="display:inline-block;width:120px;height:140px;">
              <div style="display:flex;flex-direction:column;align-items:center;">
                <img @click="addMainCategory" style="width:64px;height:64px;" :src="addImg"/>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="辅助类别" prop="subCategoryCode">
            <div v-for="(item, index) in subCategoryInfoList" :key="index" style="display:inline-block;width:120px;height:140px;">
                <div style="display:flex;flex-direction:column;align-items:center;">
                    <img style="width:64px;height:64px;" :src="item.src"/>
                    <div style="height:20px;color:000000;font-size:14px;padding-top:10px;">{{item.IMP+' '+item.text}}</div>
                </div>
            </div>
            <div style="display:inline-block;width:120px;height:140px;">
              <div style="display:flex;flex-direction:column;align-items:center;">
                <img @click="addSubCategory" style="width:64px;height:64px;" :src="addImg"/>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申报文件">
            <LocalUploadFile v-model="shenbaoFiles" :isShowTip="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="制单文件">
            <LocalUploadFile v-model="zhidanFiles" :isShowTip="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报关文件">
            <LocalUploadFile v-model="baoguanFiles" :isShowTip="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="鉴定报告">
            <LocalUploadFile v-model="jiandingFiles" :isShowTip="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="DGD">
            <LocalUploadFile v-model="dgdFiles" :isShowTip="false"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm()" type="primary" :disabled="formLoading">{{buttonTitle}}</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <MainCateGory ref="MainCateGoryRef" @success="successMainCateGory"/>
    <SubCateGory ref="SubCateGoryRef" @success="successSubCateGory"/>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { cloneDeep } from 'lodash-es'
import { CargoInfoApi, CargoInfoVO } from '@/api/business/cargoinfo'
import {testMobile} from '@/utils/test'
import {useUserStore} from '@/store/modules/user'
import {listUserByRole} from '@/api/system/user'
import {CompanyApi} from '@/api/business/company'
import {AppUserApi} from '@/api/system/appuser'
import MainCateGory from './mainCategory.vue'
import SubCateGory from './subCategory.vue'
import {formatDate} from '@/utils/formatTime'

import addImg from '@/assets/image/add.png'


/** 货物资料 表单 */
defineOptions({ name: 'CargoInfoForm' })

const userStore = useUserStore();

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  orderId: '',
  mainOrderId:'',
  subOrderId: '',
  destinationCityId: undefined,
  subDestCityId:undefined,
  serviceName:userStore.user.nickname,
  serviceGrantStatus:0,
  serviceOtherId:undefined,
  warehouseNumber:undefined,
  weight:undefined,
  volume:undefined,
  productNameMode:undefined,
  note:'',
  randomFlag:0,
  customsClearance:'',
  theGround:undefined,
  companyId:undefined,
  mainCustomerId:null,
  subCustomerId1:null,
  subCustomerId2:null,
  freight:'',
  rac:0,
  flightNumber:'',
  flightDate:'',
  mainCategoryCode:'',
  storage:1,
  subCategoryCode:'',
  specialProtection:0,
  comesDangerousBag:0,
})
const formRules = reactive({
  mainOrderId: [{ required: true, message: '主订单号不能为空', trigger: 'blur' }],
  destinationCityId: [{ required: true, message: '目的地城市不能为空', trigger: 'blur' }],
  warehouseNumber: [{ required: true, message: '件数不能为空', trigger: 'blur' }],
  productNameMode:[{ required: true, message: '品名/型号不能为空', trigger: 'blur' }],
  companyId:[{ required: true, message: '客户公司不能为空', trigger: 'blur' }],
  mainCustomerId:[{ required: true, message: '主客户不能为空', trigger: 'blur' }],
  theGround:[{required: true, message: '地服不能为空', trigger: 'blur'}]
})

const shenbaoFiles = ref([])
const zhidanFiles = ref([]);
const baoguanFiles = ref([]);
const jiandingFiles = ref([]);
const dgdFiles = ref([]);

const formRef = ref() // 表单 Ref

const MainCateGoryRef = ref();

const addMainCategory = ()=>{
  MainCateGoryRef.value.open(formData.value.mainCategoryCode);
}

const mainCategoryInfoList = ref([]);
const successMainCateGory = (codes:string)=>{
  formData.value.mainCategoryCode = codes;
  mainCategoryInfoList.value = MainCateGoryRef.value.findMainCateGory(codes);
}


const SubCateGoryRef = ref();

const addSubCategory = ()=>{
  SubCateGoryRef.value.open(formData.value.subCategoryCode);
}

const subCategoryInfoList = ref([]);
const successSubCateGory = (codes:string)=>{
  formData.value.subCategoryCode = codes;
  subCategoryInfoList.value = SubCateGoryRef.value.findMainCateGory(codes);
}


const kefuList = ref([]);
const initKefu = async ()=>{
  kefuList.value = await listUserByRole(3);
}

const comList = ref([]);
const getCompanyList = async () => {
    let data = await CompanyApi.getCompanyList({})
    comList.value = data;
}

const companyId = ref(0);
const companyChange = (value)=>{
  companyId.value = value;
  if(value){
    formData.value.subCustomerId1 = null;
    formData.value.subCustomerId2 = null;
    formData.value.mainCustomerId = null;
    getAppUserList();
  }else{
    appuserList.value = [];
    formData.value.subCustomerId1 = null;
    formData.value.subCustomerId2 = null;
    formData.value.mainCustomerId = null;
  }
}

const appuserList = ref([])
const getAppUserList = async () => {
    let data = await AppUserApi.listCompanyUsers(companyId.value)
    appuserList.value = data;
}

const destAddressList = ref([]);
const loading1 = ref(false);
const moreAddress1 = async (query: string) => {
  let reg = /^[a-zA-Z]{1,3}$/;
  if(query) {
      if(reg.test(query)) {
        loading1.value = true;
        try{
          destAddressList.value = await CargoInfoApi.queryCityCode(query);
        }finally {
          loading1.value = false;
        }
      }else{
        destAddressList.value = [];
      }
  }else{
    destAddressList.value = [];
  }
}


const destAddressList2 = ref([]);
const loading2 = ref(false);
const moreAddress2 = async (query: string) => {
  let reg = /^[a-zA-Z]{1,3}$/;
  if(query) {
      if(reg.test(query)) {
        loading2.value = true;
        try{
          destAddressList2.value = await CargoInfoApi.queryCityCode(query);
        }finally {
          loading2.value = false;
        }
      }else{
        destAddressList2.value = [];
      }
  }else{
    destAddressList2.value = [];
  }
}

const buttonTitle = ref('');

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  if(type == 'create'){
    buttonTitle.value = '创建订单'
  }else{
    buttonTitle.value = '补充订单'
  }
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CargoInfoApi.getCargoInfo(id)
      mainCategoryInfoList.value = MainCateGoryRef.value.findMainCateGory(formData.value.mainCategoryCode);
      subCategoryInfoList.value = SubCateGoryRef.value.findMainCateGory(formData.value.subCategoryCode);
      if(formData.value.companyId){
        companyId.value = formData.value.companyId;
        getAppUserList();
      }
      if(formData.value.flightDate)
        formData.value.flightDate = formatDate(formData.value.flightDate, 'YYYY-MM-DD')
      let data = await CargoInfoApi.getCreateFile(id);
      shenbaoFiles.value = data.shenbaoFiles.map(item=>{
        return {
          id:item.fileId,
          name:item.fileName
        }
      });
      zhidanFiles.value = data.zhidanFiles.map(item=>{
        return {
          id:item.fileId,
          name:item.fileName
        }
      });
      baoguanFiles.value = data.baoguanFiles.map(item=>{
        return {
          id:item.fileId,
          name:item.fileName
        }
      });
      jiandingFiles.value = data.jiandingFiles.map(item=>{
        return {
          id:item.fileId,
          name:item.fileName
        }
      });
      dgdFiles.value = data.dgdFiles.map(item=>{
        return {
          id:item.fileId,
          name:item.fileName
        }
      });
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value;
    let subData = cloneDeep(data);
    
    if (formType.value === 'create') {
      await CargoInfoApi.createCargoInfo({...subData,...{
        shenbaoFiles: shenbaoFiles.value,
        zhidanFiles: zhidanFiles.value,
        baoguanFiles: baoguanFiles.value,
        jiandingFiles: jiandingFiles.value,
        dgdFiles: dgdFiles.value
      }})
      message.success(t('common.createSuccess'))
    } else {
      await CargoInfoApi.updateCargoInfo({...subData,...{
        shenbaoFiles: shenbaoFiles.value,
        zhidanFiles: zhidanFiles.value,
        baoguanFiles: baoguanFiles.value,
        jiandingFiles: jiandingFiles.value,
        dgdFiles: dgdFiles.value
      }})
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orderId: '',
    mainOrderId:'',
    subOrderId: '',
    destinationCityId: undefined,
    subDestCityId:undefined,
    serviceName:userStore.user.nickname,
    serviceGrantStatus:0,
    serviceOtherId:undefined,
    warehouseNumber:undefined,
    weight:undefined,
    volume:undefined,
    productNameMode:undefined,
    note:'',
    randomFlag:0,
    customsClearance:'',
    theGround:undefined,
    companyId:undefined,
    mainCustomerId:null,
    subCustomerId1:null,
    subCustomerId2:null,
    freight:'',
    rac:0,
    flightNumber:'',
    flightDate:'',
    mainCategoryCode:'',
    storage:1,
    subCategoryCode:'',
    specialProtection:0,
    comesDangerousBag:0,
  }
  mainCategoryInfoList.value = [];
  subCategoryInfoList.value = [];
  shenbaoFiles.value = [];
  zhidanFiles.value = []
  baoguanFiles.value = []
  jiandingFiles.value = []
  dgdFiles.value = []
  formRef.value?.resetFields()
}

onMounted(() => {
  initKefu();
  getCompanyList();
})
</script>
